package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.mapper.AuthMapper;
import com.atguigu.crowd.service.AdminService;
import com.autguigu.crowd.constant.CrowdConstant;
import com.autguigu.crowd.exception.LoginAccountAlreadyInUseException;
import com.autguigu.crowd.exception.LoginAccountAlreadyInUseForUpdateException;
import com.autguigu.crowd.exception.LoginFailedException;
import com.autguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * admin的业务接口实现类
 *
 * @author wmb
 *
 * @since 2021-1-16
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    private static Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    @Qualifier("adminMapper")
    private AdminMapper adminMapper;

    @Autowired
    @Qualifier("authMapper")
    private AuthMapper authMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 保存admin
     *
     * @param admin
     */
    @Override
    public void saveAdmin(Admin admin) {

        // 1.密码加密
        String password = admin.getUserPassword();
//        password = CrowdUtil.md5(password);
        password = passwordEncoder.encode(password);
        admin.setUserPassword(password);

        // 2.生成创建时间
        admin.setCreateTime(new Date());

        // 3.执行保存
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
//            e.printStackTrace();

            if (e instanceof DuplicateKeyException) {
                logger.error("保存admin时出现loginAccount重名异常");
                throw new LoginAccountAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
//        int i = 1/0;
    }

    /**
     * 查询所有admin
     *
     * @return
     */
    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    /**
     *根据login_account获取admin
     *
     * @param loginAccount
     * @param password
     *
     * @return
     */
    @Override
    public Admin getAdminByUsername(String loginAccount, String password) {

        // 1.根据登录账号查询Admin对象
        // ①创建AdminExample对象
        AdminExample adminExample = new AdminExample();
        // ②创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        // ③在Criteria对象中封装查询条件
        criteria.andLoginAccountEqualTo(loginAccount);
        // ④调用adminMapper的方法执行查询
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        // 2.判断Admin对象是否为null
        if (CollectionUtils.isEmpty(adminList)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (adminList.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        // 3.如果Admin对象为null则抛出异常
        Admin admin = adminList.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 4.如果Admin对象不为null则将数据库密码从Admin对象中取出
        String userPasswordDB = admin.getUserPassword();

        // 5.将表单提交的明文密码进行加密
        String userPasswordForm = CrowdUtil.md5(password);

        // 6.对密码进行比较
        if (!Objects.equals(userPasswordDB, userPasswordForm)) {
            // 7.如果比较结果是不一致则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 8.如果一致则返回Admin对象
        return admin;
    }

    /**
     * 根据keyword分页查询admin
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     *
     * @return
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        // 1.调用PageHelper的静态方法开启分页功能
        // 这里充分体现了PageHelper的“非侵入式”设计：原本要做的查询不必做任何修改
        PageHelper.startPage(pageNum, pageSize);

        // 2.执行查询
        List<Admin> adminList = adminMapper.selectAdminByKeyword(keyword);

        // 3.封装到PageInfo对象中
        return new PageInfo<>(adminList);
    }

    /**
     * 根据adminId删除admin
     *
     * @param adminId
     */
    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    /**
     * 根据adminId查询admin
     *
     * @param adminId
     *
     * @return
     */
    @Override
    public Admin getAdminByAdminId(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    /**
     * 更新admin
     *
     * @param admin
     */
    @Override
    public void update(Admin admin) {

        // "Selective"表示有选择地更新，对于null值的字段不更新
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                logger.error("更新admin时出现loginAccount重名异常");

                throw new LoginAccountAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }

    /**
     * 为adminId的用户分配roleIdList用户权限
     *
     * @param adminId
     * @param roleIdList
     */
    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 旧数据如下：
        // adminId  roleId
        // 1        1（要删掉）
        // 1        2（要删掉）
        // 1        3
        // 1        4
        // 1        5
        // 新数据如下：
        // 1        3（本来就有）
        // 1        4（本来就有）
        // 1        5（本来就有）
        // 1        6（新）
        // 1        7（新）
        // 为了简化操作：先根据adminId删除旧的数据，再根据roleIdList保存全部新的数据

        // 1.根据adminId删除旧的关联关系数据
        adminMapper.deleteOldRelationship(adminId);

        // 2.根据roleIdList和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0) {
            adminMapper.insertNewRelationship(adminId, roleIdList);
        }
    }

    /**
     * 保存角色-用户关系
     *
     * @param map
     */
    @Override
    public void saveRoleAuthRelationship(Map<String, List<Integer>> map) {
        // 1.获取roleId的值
        List<Integer> roleIdList = map.get("roleId");
        Integer roleId = roleIdList.get(0);

        // 2.删除旧的关联关系数据
        authMapper.deleteOldRelationship(roleId);

        // 3.获取authIdList
        List<Integer> authIdList = map.get("authIdArray");

        // 4.判断authIdList是否有效
        if (authIdList != null && authIdList.size() > 0) {
            authMapper.insertNewRelationship(roleId, authIdList);
        }
    }

    /**
     * 根据用户名获取admin
     *
     * @param username
     *
     * @return
     */
    @Override
    public Admin getAdminByLoginAccount(String username) {
        AdminExample adminExample = new AdminExample();

        AdminExample.Criteria criteria = adminExample.createCriteria();

        criteria.andLoginAccountEqualTo(username);

        return adminMapper.selectByExample(adminExample).get(0);
    }
}
